//
//  ArrayExtensions.swift
//  Fangxukanghan
//
//  Created by 常超群的MacBookPro on 2021/5/24.
//

import Foundation
public extension Array {
    /// 将一元数组分割为二元数组
    func ccq_chunked(by chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
        }
    }
    /// 将一元数组分割为二元数组(第一个的个数和其余的个数)  比较笨的方法, 循环了两次,下面有性能比较高的方法
//    func sw_chunked(by firstChunkSize: Int, otherChunkSize: Int) -> [[Element]] {
//
//        let tempArray = stride(from: 0, to: self.count, by: otherChunkSize).map { item -> [Element] in
//            if item == 0 {
//                return Array(self[item..<Swift.min(item + firstChunkSize, self.count)])
//            } else {
//                let index = firstChunkSize - otherChunkSize + item
//
//                return Array(self[index..<Swift.min(index + otherChunkSize, self.count)])
//            }
//        }
//        let array = tempArray.filter{ (item) -> Bool in
//            if item.count == 0 {
//                return false
//            } else {
//                return true
//            }
//        }
//        return array
//    }
    /// 将一元数组分割为二元数组(第一个的个数和其余的个数)比上面的方法性能好
    func ccq_chunked(by steps: (Int, Int)) -> [[Element]] {
        if self.count == 0 {
            return []
        }
        let (s1, s2) = steps
        let count = count
        var total = s1
        guard total < count else {
            return [self]
        }
        var temp = [Array(self[0..<s1])]
        while true {
            let start = total
            total += s2
            if total < count {
                temp += [Array(self[start..<total])]
            } else {
                temp += [Array(self[start..<count])]
                break
            }
        }
        return temp
    }
}
